package com.example.venue_reservation_service.utils;

import org.springframework.stereotype.Component;

import java.util.regex.Pattern;

public class PhoneUtil {

    // 中国移动号段正则表达式
    private static final String CMCC_REGEX = "^1(3[4-9]|47|5[0-27-9]|7[28]|8[2-478]|9[578])\\d{8}$";
    // 中国联通号段正则表达式
    private static final String CUCC_REGEX = "^1(3[0-2]|45|5[56]|66|7[156]|8[56])\\d{8}$";
    // 中国电信号段正则表达式
    private static final String CTCC_REGEX = "^1(3[3]|49|53|7[37]|8[019]|9[0139])\\d{8}$";

    private static final Pattern CMCC_PATTERN = Pattern.compile(CMCC_REGEX);
    private static final Pattern CUCC_PATTERN = Pattern.compile(CUCC_REGEX);
    private static final Pattern CTCC_PATTERN = Pattern.compile(CTCC_REGEX);

    /**
     * 校验手机号是否合法
     * @param phoneNumber 待校验的手机号
     * @return 如果手机号合法返回 true，否则返回 false
     */
    public static boolean isValidPhoneNumber(String phoneNumber) {
        if (phoneNumber == null) {
            return false;
        }
        return CMCC_PATTERN.matcher(phoneNumber).matches() ||
                CUCC_PATTERN.matcher(phoneNumber).matches() ||
                CTCC_PATTERN.matcher(phoneNumber).matches();
    }

    public static String maskEmail(String email) {
        if (email == null || email.isEmpty()) {
            return "未认证邮箱信息";
        }

        int atIndex = email.indexOf('@');
        if (atIndex <= 0 || atIndex >= email.length() - 1) {
            // 如果没有@符号或者@符号位置不合法，直接返回原字符串
            return email;
        }

        // 获取@符号前面的部分
        String username = email.substring(0, atIndex);
        // 获取@符号后面的部分
        String domain = email.substring(atIndex);

        // 替换为6个星号
        return "******" + domain;
    }

    // 手机号脱敏
    public static String maskPhone(String phone) {
        if (phone == null || phone.length() != 11) return phone;
        return phone.substring(0, 3) + "****" + phone.substring(7);
    }

}
